package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户端微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {

        //1. openid，通过微信官方接口获取
        Map<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid()); //小程序id
        param.put("secret", weChatProperties.getSecret()); //小程序密钥
        param.put("js_code", userLoginDTO.getCode()); //授权码
        param.put("grant_type", "authorization_code"); //授权类型，固定值
        //发送请求
        String body = HttpClientUtil.doGet(WX_LOGIN, param);
        String openid = (String) JSONObject.parseObject(body).get("openid");

        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //2. id，用户id
        //向user表中添加一条数据，主要就是保存openid
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            //说明表中没有openid，是新用户，添加操作，其实就是注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //添加操作
            userMapper.insert(user);  //主键自增返回
        }

        //3. token
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(), //jwt加密密钥
                jwtProperties.getUserTtl(),  //jwt有效期
                claims);

        return UserLoginVO.builder()
                .openid(openid)
                .id(user.getId())
                .token(token)
                .build();
    }
}
